using UnityEngine;

namespace GameKitUnity
{
    public class Singleton<T> : MonoBehaviour where T : Component
    {
        private static T _instance;
        private static bool _instanceSetup;

        public static T Instance
        {
            get
            {
                if (!_instanceSetup)
                {
                    _instance = (T)FindObjectOfType(typeof(T));
                    if (_instance == null)
                    {
                        _instance = SetupInstance();
                    }
                }

                _instanceSetup = true;
                return _instance;
            }
        }

        public void Awake()
        {
            RemoveDuplicates(); // 避免重复创建多次启动执行Start()方法，如跳转挂载单例脚本的场景时
        }

        private static T SetupInstance()
        {
            _instance = (T)FindObjectOfType(typeof(T));
            if (_instance == null)
            {
                var gameObj = new GameObject
                {
                    name = typeof(T).Name
                };
                _instance = gameObj.AddComponent<T>();
                DontDestroyOnLoad(gameObj);
            }

            _instanceSetup = true;
            return _instance;
        }

        private void RemoveDuplicates()
        {
            if (_instance == null)
            {
                _instance = this as T;
                DontDestroyOnLoad(gameObject);
                _instanceSetup = true;
            }
            else
            {
                Destroy(gameObject);
            }
        }
    }
}